#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/6/13 13:53
# @Author  : lsy
# @FileName: app.py
# @Software: PyCharm
# @Function:
# 1、首页
# 2、详情页
# 3、播放页
# 4、下载页
import threading
import webbrowser

from flask import Flask, request, render_template
import json
import requests
import urllib3
import os

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

app = Flask(__name__)
# 确保静态文件目录正确配置
app.static_folder = 'static'
# 注册 max 和 min 函数到 Jinja2 环境
app.jinja_env.globals.update(max=max, min=min)


@app.route("/", methods=['GET'])
def index():
    all_params = dict(request.args)
    # 如果没有传递任何参数 则说明是登录首页查看信息
    if len(all_params) == 0:
        datalist = []
        # 最新更新的6个视频
        res = requests.get(url='https://360zy.com/api.php/provide/vod/?ac=detail&h=24', timeout=5).text
        data = json.loads(res)
        data_list = data['list']
        i = 0
        for info in data_list:
            # 电影名
            video_name = info['vod_name'].strip()
            # 上映时间
            video_release_time = info['vod_year']
            # 封面
            video_cover = info['vod_pic']
            # 类型
            vod_class = info['vod_class']
            # 更新进度
            vod_remarks = info['vod_remarks']
            # id
            vod_id = info['vod_id']
            data_info = {"video_name": video_name, "video_release_time": video_release_time, "video_cover": video_cover,
                         "vod_class": vod_class, "vod_remarks": vod_remarks, "vod_id": vod_id}
            datalist.append(data_info)
            i += 1
            if i >= 6:
                # print(data_info)
                break
        return render_template('index.html', datalist=datalist)
    else:
        # 点击导航的电影 动作 等影片跳转
        datalist = []
        t1 = all_params['t1']
        t2 = all_params['t2']
        try:
            pg = all_params['page']
        except Exception as e:
            pg = 1
        res = requests.get(
            url='https://360zy.com/api.php/provide/vod/?ac=detail&t={}&t={}&pg={}'.format(t1, t2, pg),
            timeout=5).text
        data = json.loads(res)
        total_pages = int(data['pagecount'])
        current_page = int(data['page'])
        data_list = data['list']
        for info in data_list:
            # 电影名
            video_name = info['vod_name'].strip()
            # 上映时间
            video_release_time = info['vod_year']
            # 封面
            video_cover = info['vod_pic']
            # 类型
            vod_class = info['vod_class']
            # 更新进度
            vod_remarks = info['vod_remarks']
            # id
            vod_id = info['vod_id']
            data_info = {"video_name": video_name, "video_release_time": video_release_time, "video_cover": video_cover,
                         "vod_class": vod_class, "vod_remarks": vod_remarks, "vod_id": vod_id}
            datalist.append(data_info)
        return render_template('movie_t.html', datalist=datalist, t1=t1, t2=t2, current_page=current_page,
                               total_pages=total_pages)


@app.route("/movie", methods=['GET'])
def movie():
    datalist = []
    data_info = {}
    all_params = dict(request.args)
    # 最新更新模块 点击查看全部
    if len(all_params) == 0 or 'id' not in all_params.keys():
        try:
            pg = all_params['page']
        except Exception as e:
            pg = 1
        res = requests.get(url='https://360zy.com/api.php/provide/vod/?ac=detail&pg={}'.format(pg), timeout=5).text
        data = json.loads(res)
        total_pages = int(data['pagecount'])
        current_page = int(data['page'])
        data_list = data['list']
        for info in data_list:
            # 电影名
            video_name = info['vod_name'].strip()
            # 上映时间
            video_release_time = info['vod_year']
            # 封面
            video_cover = info['vod_pic']
            # 类型
            vod_class = info['vod_class']
            # 更新进度
            vod_remarks = info['vod_remarks']
            # id
            vod_id = info['vod_id']
            data_info = {"video_name": video_name, "video_release_time": video_release_time, "video_cover": video_cover,
                         "vod_class": vod_class, "vod_remarks": vod_remarks, "vod_id": vod_id}
            datalist.append(data_info)
        return render_template('movie.html', datalist=datalist, current_page=current_page, total_pages=total_pages)
    else:
        # 点击具体的某个影片 进入详情页
        episodes = []
        down_url_dict = {}
        ids = all_params['id']
        res = requests.get(url='https://360zy.com/api.php/provide/vod/?ac=detail&ids={}'.format(ids),
                           timeout=5).text
        data = json.loads(res)
        data_list = data['list']
        for info in data_list:
            # 名称
            vod_name = info['vod_name']
            # 类型
            vod_class = info['vod_class']
            # 封面
            vod_pic = info['vod_pic']
            # 导演
            vod_director = info['vod_director']
            # 主演
            vod_actor = info['vod_actor']
            # 豆瓣评分
            vod_douban_score = info['vod_douban_score']
            # 选集
            vod_remarks = info['vod_remarks']
            # 简介
            try:
                vod_content = info['vod_content'].split('>')[1].split('<')[0]
            except Exception as e:
                vod_content = ''
                print(e)
            # 播放地址
            vod_play_url = info['vod_play_url']
            # 类型
            type_name = info['type_name']
            # 上映时间
            vod_pubdate = info['vod_pubdate']

            # 切割标识
            video_play_url = info['vod_play_url']
            video_paly_list = video_play_url.split('#')
            try:
                for key in video_paly_list:
                    k = key.split('$')[0]
                    v = key.split('$')[1]
                    episodes.append([k, v])
            except Exception as e:
                print(e)
            # print(episodes)
            data_info = {"vod_name": vod_name, "vod_class": vod_class, "vod_pic": vod_pic,
                         "vod_actor": vod_actor, "vod_douban_score": vod_douban_score, "vod_remarks": vod_remarks,
                         "vod_content": vod_content, "vod_play_url": vod_play_url, "type_name": type_name,
                         "vod_director": vod_director, "vod_pubdate": vod_pubdate}
        return render_template('detail.html', data_info=data_info, episodes=episodes)


@app.route("/search", methods=['GET'])
def search():
    datalist = []
    all_params = dict(request.args)
    # 最新更新模块 点击查看全部
    if len(all_params) != 0:
        wd = all_params['keyword']
        try:
            pg = all_params['page']
        except Exception as e:
            pg = 1
                            # https://search.lziapi.com/json-api/?dname=liangzi&key=%E4%BD%A0%E5%A5%BD&count=50
        res = requests.get(url='https://360zy.com/api.php/provide/vod/?ac=detail&wd={}&pg={}'.format(wd, pg),
                           timeout=5).text
        data = json.loads(res)
        total_pages = int(data['pagecount'])
        current_page = int(data['page'])
        data_list = data['list']
        for info in data_list:
            # 电影名
            video_name = info['vod_name'].strip()
            # 上映时间
            video_release_time = info['vod_year']
            # 封面
            video_cover = info['vod_pic']
            # 类型
            vod_class = info['vod_class']
            # 更新进度
            vod_remarks = info['vod_remarks']
            # id
            vod_id = info['vod_id']
            data_info = {"video_name": video_name, "video_release_time": video_release_time, "video_cover": video_cover,
                         "vod_class": vod_class, "vod_remarks": vod_remarks, "vod_id": vod_id}
            datalist.append(data_info)
        return render_template('movie_search.html', datalist=datalist, wd=wd, current_page=current_page,
                               total_pages=total_pages)


if __name__ == '__main__':
    def open_browser():
        webbrowser.open_new('http://127.0.0.1:5000')

    # 仅在主进程中启动浏览器（避免重新加载器触发多次）
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # 启动 Flask 应用前先开启一个线程来打开浏览器（延迟1秒确保服务启动完成）
        threading.Timer(1, open_browser).start()

    # 以单线程模式启动，避免多进程冲突
    app.run(debug=False)
